#!/usr/bin/env python
#encoding=utf-8

# __author__ test
# __time__ 2018-4-25

import sys
import paramiko
import time
import json
import commands
import ast
import threading

reload(sys)
sys.setdefaultencoding('utf-8')
lock=threading.Lock()

		
#将脚本传到服务器,并解压
def transRemote(ip,user,password):
	try:
		transport = paramiko.Transport((ip,22))
		transport.connect(username=user, password=password)
		sftp = paramiko.SFTPClient.from_transport(transport)

		ssh = paramiko.SSHClient()
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		ssh.connect(ip, 22, username=user, password=password, timeout=200)
		stdin, stdout, stderr=ssh.exec_command("pwd")
		path=stdout.read().strip("\n")

		sftp.put('/home/chenran01/fanyingjie/mysite/jixianjiancha/check/jixianjiancha.tar.gz', '%s/jixianjiancha.tar.gz'%path)
		print u"[*]将脚本传送到远程服务器"

		stdin, stdout, stderr=ssh.exec_command('tar -xvf %s/jixianjiancha.tar.gz'%path)
		print u"[*]在远程服务器上解压脚本"
		ssh.close()
		sftp.close()
		return True
	except Exception as e:
		print e
	return False


#循环遍历脚本
def remote_ssh(ip,user,password,script):
	try:
		ssh = paramiko.SSHClient()
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		ssh.connect(ip, 22, username=user, password=password, timeout=200)
		stdin, stdout, stderr=ssh.exec_command("pwd")
		path=stdout.read().strip("\n")
		print("python %s/jixianjiancha/%s"%(path,script))
		stdin, stdout, stderr=ssh.exec_command("python %s/jixianjiancha/%s"%(path,script))
		result=stdout.read()
		ssh.close()
		return result
	except Exception as e:
		pass
	return {}

def getScriptNums():
	f=open("/home/chenran01/fanyingjie/mysite/jixianjiancha/check/script.txt",'r')
	result=[line.strip("\r").strip("\n").strip() for line in f.readlines()]
	return len(result),result

